package geppetto.phraseTable.phrase.feature.global;

import geppetto.decoder.TranslationHypothesis;
import geppetto.decoder.scores.GraphPhraseProductScore;
import geppetto.decoder.scores.NumberOfOptionsScore;
import geppetto.phraseTable.PhraseTable;
import geppetto.phraseTable.phrase.Phrase;
import geppetto.phraseTable.phrase.feature.LexicalWeightingFeature;
import geppetto.phraseTable.resource.TranslationGraphResource;

import java.util.LinkedList;

public class PhraseBasedLexicalWeightingWeightedAverageCalc implements AbstractGlobalFeatureCalc {
	protected final static String FEATURE = "pwavgweight";
	protected final static String FEATURE_2 = "rpwavgweight";
	protected TranslationGraphResource translationGraph;
	protected boolean reverse = false;
	protected int order;
	
	public PhraseBasedLexicalWeightingWeightedAverageCalc(int order,
			TranslationGraphResource translationGraph, boolean reverse) {
		super();
		this.translationGraph = translationGraph;
		this.reverse = reverse;
		this.order = order;
	}

	@Override
	public void calculateFeature(Phrase phrase, PhraseTable table) {
		LinkedList<TranslationHypothesis> hyps = translationGraph.getFinalHyps();
		NumberOfOptionsScore lengthScore = (NumberOfOptionsScore)translationGraph.getScore(TranslationGraphResource.NUMBER_OF_OPTIONS);
		GraphPhraseProductScore pweightingScore = (GraphPhraseProductScore)translationGraph.getScore(TranslationGraphResource.PHRASE_WEIGHTING);
		GraphPhraseProductScore rpweightingScore = (GraphPhraseProductScore)translationGraph.getScore(TranslationGraphResource.REVERSE_PHRASE_WEIGHTING);
		
		double longestPath = 1;
		for(TranslationHypothesis h : hyps){
			double length = lengthScore.getNumberOfOptionsForHpy(h);
			if(length>longestPath){
				longestPath = length;
			}
		}
		
		double numberOfLongestPaths = 0;
		double pweight = 0;
		double rpweight = 0;
		for(TranslationHypothesis h : hyps){
			double length = lengthScore.getNumberOfOptionsForHpy(h);
			pweight += pweightingScore.getScore(h) * length / longestPath;
			rpweight += rpweightingScore.getScore(h) * length / longestPath;
			numberOfLongestPaths+=length;
		}
		
		if(reverse){
			phrase._features.addFeature(FEATURE_2, new LexicalWeightingFeature(rpweight/numberOfLongestPaths), order);			
		}
		else{
			phrase._features.addFeature(FEATURE, new LexicalWeightingFeature(pweight/numberOfLongestPaths), order);			
		}
	}

}
